package com.ruoyi.td.service.impl;

import com.fasterxml.jackson.core.type.TypeReference;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.utils.JsonUtils;
import com.ruoyi.td.entity.DevicePropertyCache;
import com.ruoyi.td.entity.DevicePropertyLogQueryBo;
import com.ruoyi.td.service.IDeviceInfoData;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

@Service
public class DeviceInfoDataCache implements IDeviceInfoData {

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Override
    public void saveProperties(String deviceId, Map<String, DevicePropertyCache> properties) {
        Map<String, DevicePropertyCache> old = getProperties(deviceId);
        old.putAll(properties);
        redisTemplate.opsForValue().set(getPropertyCacheKey(deviceId),
                JsonUtils.toJsonString(new PropertyCacheInfo(System.currentTimeMillis(), old))
        );
    }

    public Map<String, DevicePropertyCache> getProperties(String deviceId) {
        return getPropertyCacheInfo(deviceId).getProperties();
    }

    private PropertyCacheInfo getPropertyCacheInfo(String deviceId) {
        String json = redisTemplate.opsForValue().get(getPropertyCacheKey(deviceId));
        if (StringUtils.isBlank(json)) {
            return new PropertyCacheInfo(0, new HashMap<>());
        }
        return JsonUtils.parseObject(json, new TypeReference<>() {
        });
    }


    private String getPropertyCacheKey(String deviceId) {
        return String.format("tag:property:%s", deviceId);
    }
    @Data
    @NoArgsConstructor
    @AllArgsConstructor
    private static class PropertyCacheInfo {

        private long updateTime;

        private Map<String, DevicePropertyCache> properties;

    }


    @Override
    public void findDevicePropertyHistory(DevicePropertyLogQueryBo logQueryBo) {
    }
}
